<?php
/**
 * set item=value
 */

X::import('Application.Modles.Command');

class CSet extends Command {
	/**
	 * @param string $paramString
	 * @return CSet
	 */
	public function parserParamString($paramString=''){
		$this->arguments = explode(' ', trim($paramString));
		return $this;
	}
	
	/**
	 * @return CSet
	 */
	public function run(){
		if ( XUser::STATUS_OFFLINE == X::app()->user->status ){
			$this->result->errno = XErrorCode::USER_OFFLINE;
			$this->result->error = 'User offline';
			return $this;	
		}
		
		$update = explode('=', $this->arguments[0]);
		$field = $update[0];
		$value = $update[1];
			
		if ( X::app()->session->has('CurrentTodo')) {
			$tableName = 'todo';
			$itemId = X::app()->session->CurrentTodo;
		}
		else if ( X::app()->session->has('CurrentProject') ){
			$tableName = 'project';
			$itemId = X::app()->session->CurrentProject;
		}
		else {
			$this->result->errno = XErrorCode::WRONG_ARGUMENT;
			$this->result->error = 'No project has been selected.';
			return $this;
		}
		
		$db = new Database();
		$result = $db->SqlBuilder
			->update($tableName)
			->set(array($field=>$value))
			->where('id='.$itemId.' && owner='.X::app()->user->account)
			->execute();
		
		if ( $result->hasError() ){
			$this->result->errno = XErrorCode::DATABASE;
			$this->result->error = $result->error();
		}
		
		return $this;
	}
}
?>